package com.app.couponsharelife.ui.adapter

import android.graphics.drawable.BitmapDrawable
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.data.bean.ImageShareBean
import com.app.couponsharelife.databinding.GoodSharePicItemBinding
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.utils.AppUtils

/**
 * Created by guluwa on 2018/12/2.
 */
class GoodSharePicAdapter(var list: List<Any>, val listener: OnClickListener) :
        RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    var num = 1

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return ViewHolder(DataBindingUtil.inflate(
                LayoutInflater.from(parent.context), R.layout.good_share_pic_item, parent, false))
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val bean = list[position] as ImageShareBean

        val width = AppUtils.getDisplayMetrics(holder.itemView.context).widthPixels
        Glide.with(holder.itemView).asBitmap()
                .apply(RequestOptions().centerCrop().override(width, width))// 不使用内存缓存 不使用磁盘缓存
                .load(if (bean.image is String) (bean.image as String).replace(" ", "") else bean.image)
                .into((holder as ViewHolder).databinding.ivSharePic)

        if (bean.select) {
            holder.databinding.ivSharePicSelect.setImageResource(R.drawable.imag_duihao_red)
        } else {
            holder.databinding.ivSharePicSelect.setImageResource(R.drawable.ic_act_good_share_no_select)
        }
    }

    inner class ViewHolder(val databinding: GoodSharePicItemBinding) : RecyclerView.ViewHolder(databinding.root) {
        init {
            databinding.ivSharePic.setOnClickListener {
                if (adapterPosition != -1) listener.click(0, adapterPosition)
            }
            databinding.ivSharePicSelect.setOnClickListener {
                if (adapterPosition != -1) {
                    (list[adapterPosition] as ImageShareBean).select = !(list[adapterPosition] as ImageShareBean).select
                    if ((list[adapterPosition] as ImageShareBean).select) {
                        num++
                        if (databinding.ivSharePic.drawable != null)
                            (list[adapterPosition] as ImageShareBean).bitmap = (databinding.ivSharePic.drawable as BitmapDrawable).bitmap
                    } else
                        num--
                    notifyItemChanged(adapterPosition)
                }
            }
        }
    }
}